package com.define.ssh.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlUtil {

	/**
	 * @description 将xml字符串转换成map
	 * @param xml
	 * @return Map
	 */
	public static Map readStringXmlOut(String xml) {
		final Map map = new HashMap();
		Document doc = null;
		try {
			// 将字符串转为XML
			doc = DocumentHelper.parseText(xml);
			// 获取根节点
			final Element rootElt = doc.getRootElement();
			// 拿到根节点的名称
			// System.out.println("根节点：" + rootElt.getName());
			// 获取根节点下的子节点head
			final Iterator iter = rootElt.elementIterator();
			// 遍历节点
			while (iter.hasNext()) {
				final Element recordEle = (Element) iter.next();
				map.put(recordEle.getName(), recordEle.getText());

			}
		} catch (final DocumentException e) {
			e.printStackTrace();
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static void main(String[] args) {
		final String xmlString = "<?xml version=\"1.0\" encoding=\"gb2312\" ?><returnsms>"
				+ "<returnstatus>Faild</returnstatus>"
				+ "<message>用户名或密码错误</message>"
				+ "<remainpoint>0</remainpoint>"
				+ "<taskID>0</taskID>"
				+ "<successCounts>0</successCounts></returnsms>";

		final Map map = readStringXmlOut(xmlString);
		final Iterator iters = map.keySet().iterator();
		while (iters.hasNext()) {
			final String key = iters.next().toString(); // 拿到键
			final String val = map.get(key).toString(); // 拿到值
			System.out.println(key + "=" + val);
		}
	}
}
